package com.itheima.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

import static java.lang.Class.forName;

public class jdbcUtils {
    private  static String driverClass;
    private  static String url;
    private  static String username;
    private  static String password;

    //1.声明一个私有构造函数
    private jdbcUtils(){
        // 不让用户new该对象
    };
    //2.静态代码块中加载资源
    static {
        //-1.加载config.properties文件中的数据库连接四要素
        //默认会从classes编译目录下开始文件
        InputStream is = jdbcUtils.class.getClassLoader().getResourceAsStream("config.properties");
        Properties ps = new Properties();
        try {
            ps.load(is);
            String driverClass = ps.getProperty("driverClass");
            String url = ps.getProperty("url");
            String username = ps.getProperty("username");
            String password = ps.getProperty("password");
            //加载驱动
            Class.forName(driverClass);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //3.获取连接
    public static  Connection getConnection(){
    Connection conn =null;
        try {
        conn=    DriverManager.getConnection(url,username,password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

    //4.释放资源
    public static void close(Connection conn, Statement st, ResultSet rs) {
        if (conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (st != null){
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
